package com.example.demo.tool.netty.chat;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatServerHandler extends SimpleChannelInboundHandler<MyMessageProtocol> {

    /**
     * 维护了所有的连接到server的Channel
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );


    /**
     * 客户端连接,用户上线
     * @param channelHandlerContext
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        Channel channel = channelHandlerContext.channel();
        String address = channel.remoteAddress().toString();

        Date now  = new Date();
        String currentTime = sdf.format(now);

        String message = "{1} 用户{0}上线了";
        message = MessageFormat.format(message, address, currentTime);
        System.out.println(message);

        MyMessageProtocol chatMessageProtocol = new MyMessageProtocol();
        chatMessageProtocol.setContent(message.getBytes());
        chatMessageProtocol.setLen(message.getBytes().length);

        // 告诉其他用户，当前有用户上线了
        channelGroup.writeAndFlush(chatMessageProtocol);

        // 将当前通道放入到通道组里
        channelGroup.add(channel);
    }

    /**
     * 客户端断开连接,用户下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelInactive();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyMessageProtocol myMessage) throws Exception {
        Channel channel = channelHandlerContext.channel();
        String address = channel.remoteAddress().toString();

        Date now  = new Date();
        String currentTime = sdf.format(now);

        // 内容
        String s = new String(myMessage.getContent());

        System.out.println("服务端收到客户端" + address + "的消息：" + s);

        // 通知其他客户端
        channelGroup.forEach(ch -> {
            MyMessageProtocol chatMessageProtocol = new MyMessageProtocol();

            // 当前用户自己
            String chatMessage;
            if (ch == channel) {
                chatMessage = currentTime + " [自己]发送了一条消息：" + s;
                chatMessageProtocol.setContent(chatMessage.getBytes());
                chatMessageProtocol.setLen(chatMessage.getBytes().length);
                ch.writeAndFlush(chatMessageProtocol);
                // 写回客户端
            } else {
                chatMessage = currentTime + " [用户]" + address + "发送了一条消息：" + s;
                chatMessageProtocol.setContent(chatMessage.getBytes());
                chatMessageProtocol.setLen(chatMessage.getBytes().length);
                ch.writeAndFlush(chatMessageProtocol);
            }
        });
    }
}
